package com.itheima.d6_tcp3;

import java.io.*;
import java.net.Socket;

public class SeverThread implements Runnable{
    private Socket socket;
    public SeverThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        BufferedReader bufferedReader = null;
        try {
            // 3、从socket通信管道中得到一个字节输入流。
            InputStream inputStream = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(inputStream);
            // 4、把原始的字节输入流包装成高效的输入流
            bufferedReader = new BufferedReader(isr);


            // 5、使用数据输入流读取客户端发送过来的消息
            while (true) {
                String s = bufferedReader.readLine();
                if (s == null) {
                    Server.list.remove(socket);
                    break;
                }
                System.out.println("服务端接收到的消息：" + s);
                for (Socket otherSocket : Server.list) {
                    if(otherSocket != socket){
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(otherSocket.getOutputStream()));
                        bw.write(s);
                        bw.newLine();
                        bw.flush();

                    }
                }
            }
        } catch (IOException e) {
//            throw new RuntimeException(e);
            System.out.println("客户端断开了...");
        } finally {
            // 6、释放资源
            if (bufferedReader != null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
